﻿using NiceJson;
using UnityEngine;

namespace Game
{
    public class ConfigEntity : CommonEntity
    {
        protected JsonObject _configJsonObject;
        
        private ResourceComponent _resourceComp;
        private string _url;
        
        public ConfigEntity(string url)
        {
            _url = url;
            _resourceComp = AddComponent<ResourceComponent>();
            _resourceComp.Completed += OnResLoadCompleted;
        }

        public void Load()
        {
            _resourceComp.Load(_url);
        }

        protected virtual void InitConfig()
        {
        }
        
        private void OnResLoadCompleted()
        {
            _resourceComp.Completed -= OnResLoadCompleted;
            _configJsonObject = (JsonObject) JsonNode.ParseJsonString(_resourceComp.GetResource(_url).GetAsset<TextAsset>().text);
            InitConfig();
            Emit(CommonEntityEvent.OnCompleted);
        }
    }
}